package com.lc.app.androidfirst;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabaseCorruptException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.SeekBar;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.lc.app.androidfirst.userdefine.Constants;
import com.lc.app.androidfirst.userdefine.activity.ContentProviderActivity;
import com.lc.app.androidfirst.userdefine.activity.DrawPictureActivity;
import com.lc.app.androidfirst.userdefine.activity.ForResultActivity;
import com.lc.app.androidfirst.userdefine.activity.GetContactsActivity;
import com.lc.app.androidfirst.userdefine.activity.LoginActivity;
import com.lc.app.androidfirst.userdefine.activity.SDExplorerActivity;
import com.lc.app.androidfirst.userdefine.activity.ShowColorActivity;
import com.lc.app.androidfirst.userdefine.view.DrawView;
import com.lc.app.androidfirst.userdefine.view.DrawView2;
import com.lc.app.androidfirst.userdefine.view.HandleMessageActivity;
import com.lc.app.androidfirst.userdefine.view.TabHostActivity;

import java.util.ArrayList;
import java.util.Date;


public class MainActivity extends ActionBarActivity {
    private TextView showContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showContent = (TextView) findViewById(R.id.showContent);
        showContent.setText(R.string.introduce);
        showContent.setTextColor(getResources().getColor(R.color.content1));
        //Test Radio
        Button testRadio = (Button) findViewById(R.id.testRadio);
        testRadio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setContentView(R.layout.activity_radio_checkbox);
            }
        });
        //Test Toggle
        final Button testToggle = (Button) findViewById(R.id.testToggle);
        testToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               testToggleButton();
            }
        });


        //Test Image View
        final Button testImageView = (Button) findViewById(R.id.testImageView);
        testImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                testImageView();
            }
        });

        //Test AutoComplete
        Button btnAutoComplete = (Button) findViewById(R.id.testAutoComplete);
        btnAutoComplete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                testAutoComplete();
            }
        });

        //Test Spinner
        Button btnSpinner = (Button) findViewById(R.id.testSpinner);
        btnSpinner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                testSpinner();
            }
        });

        //Test Progress Bar
        Button btnProgressBar = (Button) findViewById(R.id.testProgressBar);
        btnProgressBar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                testProgressBar();
            }
        });

        //Test Seek Bar
        Button testSeekBar = (Button) findViewById(R.id.testSeekBar);
        testSeekBar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                testSeekBar();
            }
        });

        //Test Host Tab b`
        Button btnTestTabHost = (Button) findViewById(R.id.testTabHost);
        btnTestTabHost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                testTabHost();
            }
        });

        //Test Dialog
        Button btnTestDialog = (Button) findViewById(R.id.testDialog);
        btnTestDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testDialog();
            }
        });

        //Test Custom Toast
        Button btnTestCustomToast = (Button) findViewById(R.id.testCustomToast);
        btnTestCustomToast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testCustomToast();
            }
        });

        //Test Notifaction
        Button btnTestNotifaction = (Button)findViewById(R.id.testNotification);
        btnTestNotifaction.setOnClickListener(new MyListener("show"));

        //Test Cancel Notifaction
        Button btnTestCancelNotification = (Button) findViewById(R.id.testCancelNotification);
        btnTestCancelNotification.setOnClickListener(new MyListener("cancel"));

        //Test User Defined View
        Button btnTestUserDefineView = (Button) findViewById(R.id.testUserDefineView);
        btnTestUserDefineView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testUserDefineCustomView();
            }
        });

        //Test Plane Game
        Button btnTestPlane = (Button) findViewById(R.id.testPlane);
        btnTestPlane.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,PlaneGameActivity.class);
                startActivity(intent);
            }
        });

        //Test Configuration
        Button btnTestConfiguration = (Button) findViewById(R.id.testConfiguration);
        btnTestConfiguration.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testConfiguration();
            }
        });

        //Test Change Configuration
        Button btnTestChangeConfiguration = (Button) findViewById(R.id.testChangeConfiguration);
        btnTestChangeConfiguration.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testChangeConfiguration();
            }
        });


        //Test Handle Message
        Button btnTestHandleMessage = (Button) findViewById(R.id.testHandleMessage);
        btnTestHandleMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, HandleMessageActivity.class);
                startActivity(intent);
            }
        });

        //Test Login
        Button btnTestLogin = (Button) findViewById(R.id.testLogin);
        btnTestLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                startActivity(intent);
            }
        });

        //Test Start Activity For Result
        Button btnTestStartActivityForResult = (Button) findViewById(R.id.testStartActivityForResult1);
        btnTestStartActivityForResult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ForResultActivity.class);
                startActivityForResult(intent, REQ_CODE1);
//                Intent intent = new Intent();
//                intent.setAction("MyTestAction");
//                startActivityForResult(intent, REQ_CODE1);
            }
        });
        Button btnTestStartActivityForResult2 = (Button) findViewById(R.id.testStartActivityForResult2);
        btnTestStartActivityForResult2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(MainActivity.this, ForResultActivity.class);
//                startActivityForResult(intent,REQ_CODE2);
                ComponentName componentName = new ComponentName(MainActivity.this,ForResultActivity.class);
                Intent intent = new Intent();
                intent.setComponent(componentName);
                startActivityForResult(intent, REQ_CODE2);
            }
        });

        Button btnReadContacts = (Button) findViewById(R.id.testReadContact);
        btnReadContacts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, GetContactsActivity.class);
                startActivity(intent);
            }
        });

        //Test define resources  show color
        Button btnTestShowColor = (Button) findViewById(R.id.testShowColorBtn);
        btnTestShowColor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ShowColorActivity.class);
                startActivity(intent);
            }
        });

        //Test Canvas and Paint
        Button btnTestCanvas = (Button) findViewById(R.id.testCanvas);
        btnTestCanvas.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testDraw(1);
            }
        });


        //Test Draw 2D
        Button btnTestDraw2D = (Button) findViewById(R.id.testDraw2D);
        btnTestDraw2D.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               testDraw(2);
            }
        });

        Button btnTestDrawText = (Button) findViewById(R.id.testDrawText);
        btnTestDrawText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testDraw(3);
            }
        });

        Button btnTestDrawPath = (Button) findViewById(R.id.testDrawPath);
        btnTestDrawPath.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testDraw(4);
            }
        });

        //Test Draw Bitmap
        Button btnTestDrawBitmap = (Button) findViewById(R.id.testDrawBitmap);
        btnTestDrawBitmap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testDrawBitmap();
            }
        });

        //Test Draw Android
        Button btnTestDrawAndroid = (Button) findViewById(R.id.testDrawAndroid);
        btnTestDrawAndroid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testDraw(6);
            }
        });

        //Test Draw Picture
        Button btnTestDrawPicture = (Button) findViewById(R.id.testDrawPicture);
        btnTestDrawPicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testDrawPicture();
            }
        });

        Button btnTestDrawMatrix = (Button) findViewById(R.id.testDrawMatrix1);
        btnTestDrawMatrix.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testDraw(7);
            }
        });

        Button btnTestDrawShader = (Button) findViewById(R.id.testDrawShader);
        btnTestDrawShader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testDraw(8);
            }
        });

        Button btnTestAnimation = (Button) findViewById(R.id.testAnimation);
        btnTestAnimation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testAnimation();
            }
        });

        // test read and write shared preferences
        Button btnTestSharedPreferences = (Button) findViewById(R.id.testSharedPreferences);
        btnTestSharedPreferences.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ContentProviderActivity.class);
                intent.putExtra(Constants.KEY_CONTENT_PROVIDER,Constants.READ_WRITE_SHARED_PREFERENCES);
                startActivity(intent);
            }
        });

        // test read and write file
        Button btnTestFileIO = (Button) findViewById(R.id.testFile);
        btnTestFileIO.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ContentProviderActivity.class);
                intent.putExtra(Constants.KEY_CONTENT_PROVIDER,Constants.READ_WRITE_FILE);
                startActivity(intent);
            }
        });

        //test read and write sd card
        Button btnTestSDCard = (Button) findViewById(R.id.testSDCard);
        btnTestSDCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ContentProviderActivity.class);
                intent.putExtra(Constants.KEY_CONTENT_PROVIDER,Constants.READ_WRITE_SDCARD);
                startActivity(intent);
            }
        });

        //test sd card explorer
        Button btnTestSDExplorer = (Button) findViewById(R.id.testSDExplorer);
        btnTestSDExplorer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SDExplorerActivity.class);
                startActivity(intent);
            }
        });

        //test sqlite
        Button btnTestSQLite = (Button) findViewById(R.id.testSQLite);
        btnTestSQLite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               testSQLite();
            }
        });



  //     testControlViewByCode();
  //      testControlerViewByCodeAndXml();
  //      testUserDefineCustomView();
        //test linear layout
//        setContentView(R.layout.activity_linear_layout);
 //       setContentView(R.layout.activity_table_layout);
 //       setContentView(R.layout.activity_user_friendly_input);
  //      setContentView(R.layout.activity_radio_checkbox);
//        testToggleButton();
//        testImageView();
//        testAutoComplete();
//        testSpinner();
//        testProgressBar();
//        testSeekBar();
 //       testTabHost();

    }

    SQLiteDatabase db;
    ListView listView;
    EditText textInputName;
    EditText textInputPass;

    TextView hiddenIdView;
    private void testSQLite(){
        setContentView(R.layout.content_sqlite);
        listView = (ListView) findViewById(R.id.listView);
        textInputName = (EditText) findViewById(R.id.textInputName);
        textInputPass = (EditText) findViewById(R.id.textInputPass);
        hiddenIdView = (TextView) findViewById(R.id.hiddenId);
        init();

        Button btnSqliteClear = (Button) findViewById(R.id.btnSqliteClear);
        btnSqliteClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hiddenIdView.setText(null);
                textInputName.setText(null);
                textInputPass.setText(null);
            }
        });
        Button btnSqliteSave = (Button) findViewById(R.id.btnSqliteSave);
        btnSqliteSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                db = SQLiteDatabase.openOrCreateDatabase(getApplicationContext().getFilesDir() + "/my.db3", null);
                String name = null;
                String pass = null;

                if (textInputName.getText() != null && !textInputName.getText().toString().equals("") && textInputPass.getText() != null && !textInputPass.getText().toString().equals("")) {
                    name = textInputName.getText().toString();
                    pass = textInputPass.getText().toString();
                } else {
                    Toast.makeText(getApplicationContext(), "Name or Password could not be null.", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    if(hiddenIdView.getText()!= null && !hiddenIdView.getText().toString().trim().equals("")){
                        updateData(db,hiddenIdView.getText().toString(),name,pass);
                    }else{
                        insertData(db, name, pass);
                    }
                    Cursor cursor = db.rawQuery("select _id,user_name,user_pass from user_info", null);
                    inflateList(cursor);
                } catch (Exception e) {
                    try{
                        db.execSQL("drop table user_info");
                    }catch(Exception e1){
                        Toast.makeText(getApplicationContext(), "Insert error.Drop the table error.", Toast.LENGTH_SHORT).show();
                        e1.printStackTrace();
                    }
                    String sql = "create table user_info(_id integer primary key,user_name varchar(255),user_pass varchar(255))";
                    db.execSQL(sql);
                    Toast.makeText(getApplication(),"Create table.",Toast.LENGTH_SHORT).show();
                    insertData(db, name, pass);
                    Cursor cursor = db.rawQuery("select _id,user_name,user_pass from user_info", null);
                    inflateList(cursor);
                }
            }
        });


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cursor cursor = db.rawQuery("select _id,user_name,user_pass from user_info where _id = ?", new String[]{String.valueOf(id)});
                cursor.moveToFirst();
                String myId = cursor.getString(cursor.getColumnIndex("_id"));
                String userName = cursor.getString(cursor.getColumnIndex("user_name"));
                String userPass = cursor.getString(cursor.getColumnIndex("user_pass"));
                textInputName.setText(userName);
                textInputPass.setText(userPass);
                hiddenIdView.setText(myId);
            }
        });

      listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
          @Override
          public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
              AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
              builder.setTitle("Delete");
              builder.setMessage("Are you sure to delete?");
              final long myId = id;
              builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      db.execSQL("delete from user_info where _id = ?", new String[]{String.valueOf(myId)});
                      Toast.makeText(getApplicationContext(),"Delete Success",Toast.LENGTH_SHORT).show();
                      Cursor cursor = db.rawQuery("select _id,user_name,user_pass from user_info", null);
                      inflateList(cursor);
                  }
              });

              builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {

                  }
              });

              Dialog dialog = builder.create();
              dialog.show();
              return true;
          }
      });
    }

    private void init(){
        try {
            db = SQLiteDatabase.openOrCreateDatabase(getApplicationContext().getFilesDir() + "/my.db3", null);
            Cursor cursor = db.rawQuery("select _id,user_name,user_pass from user_info", null);
            inflateList(cursor);
        }catch (Exception e){

        }
    }

    private void updateData(SQLiteDatabase db,String _id,String name, String pass){
        db.execSQL("update user_info set user_name=?,user_pass=? where _id=?", new String[]{name, pass,_id});
        Toast.makeText(getApplicationContext(),"Update database.",Toast.LENGTH_SHORT).show();
    }

    private void insertData(SQLiteDatabase db,String name, String pass) {
        db.execSQL("insert into user_info(user_name,user_pass) values(?,?)", new String[]{name, pass});
        Toast.makeText(getApplicationContext(),"Insert into database.",Toast.LENGTH_SHORT).show();
    }
    private void inflateList(Cursor cursor){
       try{
           SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(),R.layout.content_user,
                   cursor,new String[]{"_id","user_name","user_pass"},new int[]{R.id.listId,R.id.listUserName,R.id.listPass});
           listView.setAdapter(adapter);
       }catch (Exception e){
           e.printStackTrace();
       }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(db!=null && db.isOpen()){
            db.close();
        }
    }

    private void testAnimation(){
        setContentView(R.layout.activity_custom_view);
        LinearLayout layout = (LinearLayout) findViewById(R.id.custom_root);
        ImageView imageView = new ImageView(getApplicationContext());
        imageView.setImageResource(R.drawable.horse_xml);
        AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
        layout.addView(imageView);
        animationDrawable.setOneShot(false);
        animationDrawable.start();
    }


    public static final int REQ_CODE1 = 1;
    public static final int REQ_CODE2 = 2;
    public static final int RES_CODE1 = 1;
    public static final int RES_CODE2 = 2;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      //  super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQ_CODE1 && resultCode == RES_CODE1){
            Bundle bundle = data.getExtras();
            String value = (String) bundle.get("data");
            showContent.setText(value);
        }else if(requestCode == REQ_CODE2 && resultCode == RES_CODE2){
            Bundle bundle = data.getExtras();
            String value = (String) bundle.get("data");
            Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).show();
        }else {
            Bundle bundle = data.getExtras();
            String value = (String) bundle.get("data");
            showContent.setText("requestCode:"+requestCode+ ",resultCode:"+resultCode+",data:"+value);
        }
    }

    private void testDrawPicture(){
        Intent intent  = new Intent(MainActivity.this, DrawPictureActivity.class);
        startActivity(intent);
    }

    private void testDrawBitmap(){
        setContentView(R.layout.activity_custom_view);
        LinearLayout layout = (LinearLayout) findViewById(R.id.custom_root);

        final DrawView2 drawView2 = new DrawView2(this,5);
        layout.addView(drawView2);
    }

    private void testDraw(int buttonType){
        setContentView(R.layout.activity_custom_view);
        LinearLayout layout = (LinearLayout) findViewById(R.id.custom_root);
        final DrawView2 drawView2 = new DrawView2(this,buttonType);
        layout.addView(drawView2);
    }



    private void testChangeConfiguration(){
        Configuration cfg = getResources().getConfiguration();
        if(cfg.orientation == Configuration.ORIENTATION_LANDSCAPE){
            MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }else if(cfg.orientation == Configuration.ORIENTATION_PORTRAIT){
            MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }else{
            showContent.setText("Unkown Orientation.");
        }
    }

    private void testConfiguration(){
        Configuration cfg = getResources().getConfiguration();
        String screen = cfg.orientation == Configuration.ORIENTATION_LANDSCAPE ? "Horizontal Screen." : "Vertical Screen.";
        String mncCode =cfg.mnc+"";
        String naniName = cfg.orientation == Configuration.NAVIGATION_NONAV ? "No direction control." : cfg.orientation == Configuration.NAVIGATION_WHEEL ? "Wheel direction control." : cfg.orientation == Configuration.NAVIGATION_DPAD ? "Direction button control." : "Track ball direction control.";
        String touchName = cfg.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH ? "No touch." : cfg.touchscreen == Configuration.TOUCHSCREEN_FINGER ? "Finger touch." : "Pen touch";

        StringBuilder sb = new StringBuilder();
        sb.append("screen:"+ screen+ "\n");
        sb.append("mnc:"+mncCode +"\n");
        sb.append("nani:"+naniName+"\n");
        sb.append("touch:"+touchName+"\n");

        showContent.setText(sb.toString());
    }

    //View bind method
    public void clickHandle(View resource) {
        Toast.makeText(getApplicationContext(), "Click Listener bind on View.", Toast.LENGTH_SHORT).show();
    }


    public static int NOTIFICATION_ID = 0x110;

    private void testCustomToast(){
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.activity_custom_toast, (ViewGroup) findViewById(R.id.custom_toast_layout_root));
        TextView textView = (TextView) layout.findViewById(R.id.testToastText);
        textView.setText("This is A toast Text", TextView.BufferType.SPANNABLE);

        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.CENTER_HORIZONTAL,0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(layout);
        toast.show();
    }


    private AlertDialog.Builder builder;
    private EditText editText;
    private void testDialog(){
        setContentView(R.layout.activity_dialog);
        Button btnTestAlertDialog = (Button) findViewById(R.id.testAlertDialog);

        editText = (EditText) findViewById(R.id.testDialogShow);
        btnTestAlertDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("测试AlertDialog");
                builder.setIcon(R.drawable.image_blue_kinoko);
                builder.setMessage("一个简单的AlertDialog");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        editText.setText("确定按钮");
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        editText.setText("取消按钮");
                    }
                });

                builder.setNeutralButton("装饰", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        editText.setText("装饰按钮");
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });

        Button btnTestNormalList = (Button) findViewById(R.id.testNormalList);
        btnTestNormalList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] colors = new String[]{"红的", "黄的", "绿的"};
                builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("普通的选择列表AlertDialog");
                builder.setItems(colors, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                editText.setText("红色");
                                break;
                            case 1:
                                editText.setText("黄色");
                                break;
                            case 2:
                                editText.setText("绿色");
                                break;
                        }
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });

        Button btnTestSingleChoice = (Button) findViewById(R.id.testSingleChoice);
        btnTestSingleChoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] colors = new String[]{"红的", "黄的", "绿的"};
                builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("普通的选择列表AlertDialog");
                builder.setSingleChoiceItems(colors, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch(which){
                            case 0:
                                editText.setText("单选红色");
                                break;
                            case 1:
                                editText.setText("单选黄色");
                                break;
                            case 2:
                                editText.setText("单选绿色");
                                break;
                        }
                    }
                });
                builder.setPositiveButton("确定",null);
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });

        Button btnTestMultiChoice = (Button) findViewById(R.id.testMultiChoice);
        btnTestMultiChoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] names = new String[]{"Java","English","SQL","Oracle"};
                final boolean[] checkStatus = new boolean[]{false, true, false, true};
                final ArrayList<Integer> choices = new ArrayList<Integer>();
                builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("一个多选列表");
                builder.setMultiChoiceItems(names, checkStatus, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        for (int i=0;i<checkStatus.length;i++){
                            if(checkStatus[i]){
                                if(!choices.contains(new Integer(i))){
                                    choices.add(new Integer(i));
                                }
                            }else{
                                if(choices.contains(new Integer(i))){
                                    choices.remove(new Integer(i));
                                }
                            }
                        }
                    }
                });

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        StringBuffer sb = new StringBuffer();
                        if (choices.size() > 0) {
                            sb.append("您选中的是：");
                            for (int i = 0; i < choices.size(); i++) {
                                sb.append(names[choices.get(i)]);
                                if (i != choices.size() - 1) {
                                    sb.append(",");
                                }
                            }

                        } else {
                            sb.append("您什么都没选中");
                        }
                        editText.setText(sb.toString());
                    }
                });

                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });


    }



    private void testTabHost(){
        Intent intent = new Intent(this, TabHostActivity.class);
        startActivity(intent);
    }

    private void testSeekBar(){
        setContentView(R.layout.activity_seek_bar);
        SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
        final ImageView imageView = (ImageView) findViewById(R.id.seekImageView);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                imageView.setImageAlpha(i);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingBar);
        final ImageView imageView1 = (ImageView) findViewById(R.id.ratingImageView);
        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
                imageView1.setImageAlpha((int) (v * 255 / 5));
            }
        });


    }


    private int[] data = new int[100];
    private int hasData = 0;
    private int status = 0;
    private void testProgressBar(){
        setContentView(R.layout.activity_progress_bar);
        final ProgressBar bar1 = (ProgressBar) findViewById(R.id.progressBar1);
        final ProgressBar bar2 = (ProgressBar) findViewById(R.id.progressBar2);

        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
               if(msg.what == 0x111){
                   bar1.setProgress(status);
                   bar2.setProgress(status);
               }
            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                while(status < 100){
                    status =doWork();
                    Message m = new Message();
                    m.what = 0x111;
                    handler.sendMessage(m);
                }
            }
        }).start();

    }

    public int doWork(){
        data[hasData ++ ] = (int) (Math.random() * 100);

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return hasData;
    }



    final int[] images = new int[]{R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4,R.drawable.image5};

    private void testSpinner(){
        setContentView(R.layout.activity_spinner);
        BaseAdapter ba2 = new BaseAdapter() {
            @Override
            public int getCount() {
                return 5;
            }

            @Override
            public Object getItem(int i) {
                return null;
            }

            @Override
            public long getItemId(int i) {
                return 0;
            }

            @Override
            public View getView(int i, View view, ViewGroup viewGroup) {
                LinearLayout linearLayout = new LinearLayout(MainActivity.this);

                ImageView imageView = new ImageView(MainActivity.this);
                imageView.setImageResource(images[i]);
                imageView.setMaxHeight(50);
                imageView.setMaxWidth(50);

                TextView textView = new TextView(MainActivity.this);
                textView.setText(i+" Test Spinner");
                textView.setTextSize(35);
                textView.setTextColor(Color.BLUE);

                linearLayout.addView(imageView);
                linearLayout.addView(textView);
                linearLayout.setOrientation(LinearLayout.HORIZONTAL);

                return linearLayout;
            }
        };

        Spinner spinner = (Spinner) findViewById(R.id.spinnerTest);
        spinner.setAdapter(ba2);
    }


    //test auto complete text view
    private void testAutoComplete(){
        setContentView(R.layout.auto_complete_spinner);
        String[] autoes = new String[]{"A brave man","Above","ahuman","bcdef","aaaa"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,autoes);
        AutoCompleteTextView act = (AutoCompleteTextView) findViewById(R.id.autoComplete);
        act.setAdapter(adapter);

        SpinnerAdapter adapter1 = adapter;
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        spinner.setAdapter(adapter1);

    }

    int currentImage1 = 0;
    private int alpha = 255;
    private void testImageView(){
        setContentView(R.layout.activity_image_view);
        final int[] images = new int[]{R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4,R.drawable.image5};
        final Button btnAdd = (Button) findViewById(R.id.iv_add);
        final Button btnMul = (Button) findViewById(R.id.iv_mul);
        final Button btnNext = (Button) findViewById(R.id.iv_next);

        final ImageView imageView1 = (ImageView) findViewById(R.id.imageView1);
        final ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);

        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (currentImage1 >= images.length - 1) {
                    currentImage1 = -1;
                }

                // if image is not recycled, recycle the imageview resource
                BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView1.getDrawable();
                if(!bitmapDrawable.getBitmap().isRecycled()){
                    bitmapDrawable.getBitmap().recycle();
                }

                imageView1.setImageBitmap(BitmapFactory.decodeResource(getResources(),images[++currentImage1]));
            }
        });

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(view == btnAdd){
                    alpha += 20;
                }

                if(view == btnMul){
                    alpha -= 20;
                }

                if(alpha >= 255){
                    alpha = 255;
                }

                if(alpha <= 0){
                    alpha = 0;
                }

                imageView1.setImageAlpha(alpha);
            }
        };
        btnAdd.setOnClickListener(listener);
        btnMul.setOnClickListener(listener);

        imageView1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView1.getDrawable();
                Bitmap bitmap = bitmapDrawable.getBitmap();
                double scale = bitmap.getWidth()/300;

                int x = (int) (motionEvent.getX() * scale);
                int y = (int) (motionEvent.getY() * scale);

//                if(x + 120 >bitmap.getWidth()){
//                    x = bitmap.getWidth()-120;
//                }
//
//                if(y + 120 >bitmap.getHeight()){
//                    y = bitmap.getHeight()-120;
//                }




                if(x+120 > bitmap.getWidth()){
                    x = bitmap.getWidth() - 120;
                }else{
                    x = x -60;
                }

                if(y+120 > bitmap.getHeight()){
                    y = bitmap.getHeight() - 120;
                }else{
                    y = y - 60;
                }

                if(x < 0 ){
                    x = 0;
                }

                if(y < 0){
                    y=0;
                }


  //              Logger.getGlobal().warning(scale +" "+ x+ "  "+y);
                imageView2.setImageBitmap(Bitmap.createBitmap(bitmap,x,y,120,120));
                imageView2.setImageAlpha(alpha);
                return true;
            }
        });


    }


    private void testToggleButton(){
        setContentView(R.layout.activity_toggle_button);
        ToggleButton btn = (ToggleButton) findViewById(R.id.mybtn1);
        final LinearLayout layout = (LinearLayout) findViewById(R.id.changedLayout);

        btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(compoundButton.isChecked()){
                    layout.setOrientation(LinearLayout.HORIZONTAL);
                }else {
                    layout.setOrientation(LinearLayout.VERTICAL);
                }
            }
        });

    }



    //test user define custom view

    boolean isUp = true;
    float newR = 15 ;
    private void  testUserDefineCustomView(){
        setContentView(R.layout.activity_custom_view);
        LinearLayout layout = (LinearLayout) findViewById(R.id.custom_root);
        final DrawView drawView = new DrawView(this);
        drawView.setMinimumHeight(800);
        drawView.setMinimumWidth(500);

        Button btn = new Button(this);
        btn.setText("Click");
        btn.setMaxHeight(20);
        btn.setMaxWidth(35);
        btn.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        btn.setGravity(Gravity.NO_GRAVITY);

        drawView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                float mX = motionEvent.getX();
                float mY = motionEvent.getY();

                if (Math.abs(mX - drawView.currentX) < 15 && Math.abs(mY - drawView.currentY) < 15 && motionEvent.getEventTime() - motionEvent.getDownTime() < 1000) {
                    newR = drawView.r;
                    if (isUp) {
                        if (newR >= 105) {
                            newR -= 30;
                            isUp = false;
                        } else {
                            newR += 30;
                        }
                    } else {
                        if (newR <= 15) {
                            newR += 30;
                            isUp = true;
                        } else {
                            newR -= 30;
                        }
                    }
                    drawView.r = newR;
                } else {
                    {
                        drawView.currentX = motionEvent.getX();
                        drawView.currentY = motionEvent.getY();

                    }
                }
                drawView.invalidate();
                return true;
            }
        });

        layout.addView(drawView);
    }


    int currentImage = 0;
    //Use Java Code and XML file to control UI
    private void testControlerViewByCodeAndXml(){
        final int[] images = new int[]{R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4,R.drawable.image5};
        setContentView(R.layout.activity_image);
        LinearLayout layout = (LinearLayout) findViewById(R.id.image_root);
        final ImageView imageView = new ImageView(this);
        layout.addView(imageView);
        imageView.setImageResource(images[0]);


        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //              Toast.makeText(getApplicationContext(),view.getId()+"",Toast.LENGTH_SHORT).show()
                if (currentImage >= images.length - 1) {
                    currentImage = -1;
                }
                imageView.setImageResource(images[++currentImage]);
            }
        });

    }

    //Use Java Code to Control UI
    private void testControlViewByCode() {
        LinearLayout layout = new LinearLayout(this);
        setContentView(layout);
        layout.setOrientation(LinearLayout.VERTICAL);
        TextView textView = new TextView(this);
        textView.setText("OK");
        Button button = new Button(this);
        button.setText("按钮");
        button.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), "Toast 提示:" + new Date(), Toast.LENGTH_SHORT).show();
            }
        });

        layout.addView(textView);
        layout.addView(button);
    }


    final int FONT_14 =0x113;
    final int FONT_16 = 0x114;
    final int FONT_18 = 0x115;

    final int PLAIN_ITEM = 0x11b;
    final int FONT_RED = 0x116;
    final int FONT_BLUE = 0x117;
    final int FONT_GREEN = 0x118;

    final int RETURN_MAIN = 0x119;
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        SubMenu subMenu = menu.addSubMenu(0,RETURN_MAIN,0,"返回主页");

        SubMenu fontMenu = menu.addSubMenu("字体大小");
        fontMenu.setIcon(R.drawable.image_hot);
        fontMenu.setHeaderIcon(R.drawable.image_blue_dot);
        fontMenu.setHeaderTitle("选择字体大小");
        fontMenu.add(0, FONT_14, 0, "14号字体");
        fontMenu.add(0, FONT_16, 0, "16号字体");
        fontMenu.add(0,FONT_18,0,"18号字体");

        MenuItem plainMenu =  menu.add(0,PLAIN_ITEM,0,"普通菜单项");
        plainMenu.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(MainActivity.this,"监听器侦测到点击了普通菜单项",Toast.LENGTH_SHORT).show();
                return true;
            }
        });


        SubMenu colorMenu = menu.addSubMenu("字体颜色");
        colorMenu.setIcon(R.drawable.image_star__circle);
        colorMenu.setHeaderIcon(R.drawable.image_star__circle);
        colorMenu.setHeaderTitle("选择字体颜色");

        colorMenu.add(0, FONT_RED, 0, "红色");
        colorMenu.add(0, FONT_BLUE, 0, "绿色");
        colorMenu.add(0, FONT_GREEN, 0, "蓝色");

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        String message = null;
        switch (id) {
            case RETURN_MAIN:
                Intent intent = new Intent(this, MainActivity.class);
                this.finish();
                startActivity(intent);
                break;
            case FONT_14:
                message = "你选中了14号字体";
                break;
            case FONT_16:
                message = "你选中了16号字体";
                break;
            case FONT_18:
                message = "你选中了18号字体";
                break;
            case FONT_RED:
                message = "你选中了红色";
                break;
            default:
                message = "没有绑定事件的菜单.";
                break;
        }
        if (message != null) {
            Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
        }
        return true;
    }


    class MyListener implements View.OnClickListener {
        private String methodName;

        public MyListener(String methodName){
            this.methodName = methodName;
        }
        @Override
        public void onClick(View v) {
            if("show".equals(this.methodName)){
                NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
                NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
                builder.setSmallIcon(R.drawable.image_notification);
                builder.setContentTitle("您有新消息");
                builder.setContentText("一个普通的通知");

                Intent intent = new Intent(MainActivity.this,TabHostActivity.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,0);
                builder.setContentIntent(pendingIntent);

                Notification notification = builder.build();
                notification.flags |= Notification.FLAG_AUTO_CANCEL;
                manager.notify(MainActivity.NOTIFICATION_ID,notification);
            }

            if("cancel".equals(this.methodName)){
                NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
                manager.cancel(MainActivity.NOTIFICATION_ID);
            }
        }
    }
}

